//
//  JWKOAuthViewController.swift
//  Weibo
//
//  Created by 姜维克 on 16/5/22.
//  Copyright © 2016年 姜维克. All rights reserved.
//

import UIKit
import SVProgressHUD

class JWKOAuthViewController: UIViewController {

    let webView = UIWebView()
    
    override func loadView() {
        super.loadView()
        view = webView
        
        //设置webView的代理
        webView.delegate = self
        setupWebView()
    }
    
    private func setupWebView(){
        let urlString = "https://api.weibo.com/oauth2/authorize"+"?client_id="+client_id+"&redirect_uri="+redirect_uri
        
        let url = NSURL(string: urlString)!
        let requset = NSURLRequest(URL: url)
        webView.loadRequest(requset)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        
        //设置导航栏
        setupNavBar()

    }
    
}

extension JWKOAuthViewController{
    
    //dismiss出去oauth
    @objc private func dismiss(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //自动填充测试账号---动态注册JS代码
    @objc private func autoTestAccount(){
        let JSstring = "document.getElementById('userId').value = 'jiangweike123123@163.com',document.getElementById('passwd').value = '123a123b321c321d'"
        webView.stringByEvaluatingJavaScriptFromString(JSstring)
    
    }
    
    //设置navigationBar的两侧item
    private func setupNavBar(){
        
        //左侧的返回item
        let leftItem = UIBarButtonItem.init(title: "返回", target: self, action: #selector(dismiss))
        navigationItem.leftBarButtonItem = leftItem
        
        //右侧的自动填充测试账号和密码
        let rightItem = UIBarButtonItem.init(title: "测试账号", target: self, action: #selector(autoTestAccount))
        navigationItem.rightBarButtonItem = rightItem
    }
    
}

extension JWKOAuthViewController:UIWebViewDelegate{
    
    //能否加载网络请求--获取授权码
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let str = request.URL?.absoluteString ?? ""//设置成了必选项
        
        let codeFlag = "code="
        
        if str.containsString(codeFlag){
            
            let range = str.rangeOfString(codeFlag)
            let index = range!.endIndex
            //MARK:-截取字符串 获取code授权码
            let code = str.substringFromIndex(index)
            
            //利用授权码去获取token值
            JWKUserAccountViewModel.sharedUserAccountViewModel.getUserAccessToken(code){(isSuccess:Bool) -> Void in
                
                if !isSuccess{
                    //请求失败
                    SVProgressHUD.showErrorWithStatus("没网了")
                    return
                }
                
                //请求成功--要切换控制器--欢迎页面
                print("要切换控制器--欢迎页面")
                
                //发送通知给appdelegate
//                UIApplication.sharedApplication().keyWindow?.rootViewController = JWKWelcomeViewController()
                NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootViewController, object: "Welcome")
            }
            
            print(code,str)
            
            return false
        }

        return true
    }
    
    
    
    //开始网络加载
    func webViewDidStartLoad(webView: UIWebView) {
       //显示用户等待指示器
        SVProgressHUD.show()
    }
    
    //结束网络加载
    func webViewDidFinishLoad(webView: UIWebView) {
       //隐藏用户等待指示器
        SVProgressHUD.dismiss()
    }
    
}
